#import "FileUploader.h"
#include "util.h"
#import "HttpServerURL.h"
#import "XmlParser.h"
#import "InfoType.h"


#define		JPEG_CONTENT_TYPE			@"image/jpeg"
#define		MP4_CONTENT_TYPE			@"video/mp4"


@implementation FileUploader

//@synthesize connection;
//@synthesize request;
@synthesize contentXMLProperty;
@synthesize anewURL1;
@synthesize userData;
@synthesize delegate;
@synthesize contentType;

@synthesize businessID;
@synthesize fileType;
@synthesize fileName;
@synthesize memberID;
@synthesize uploadServer;
@synthesize businessType;
@synthesize fileID;

-(id)init
{
	self = [super init];
	if(self)
	{
//        request=[[ASIFormDataRequest alloc] init];
		result = [[NSMutableData alloc] initWithCapacity:128];
		canceled = NO;
		scaleIfNeed = NO;
	}
	return self;
}


-(void)dealloc
{
	self.delegate = nil;
//	self.connection = nil;
	self.contentXMLProperty = nil;
	self.anewURL1 = nil;
	self.userData = nil;
	self.contentType = nil;
	[result  release];
    
//    if (request != nil){
//        request = nil;
//        [request release];
//    }
	[super dealloc];
}

-(void) uploadPic:(UIImage*) image delegate:(id <FileUploaderDelegate>)dlgt  businessType:(NSString*) bsType businessID:(NSString*) bsID fileType:(NSString*) fType fileName:(NSString*) fName memberID:(NSString*) mName
{
    self.businessID = bsID;
    self.fileType = fType;
    self.fileName = fName;
//    self.fileID = fID;
    self.memberID = mName;
    self.businessType = bsType;
    
    [self postImage:(UIImage*)image delegate:(id <FileUploaderDelegate>)dlgt userData:nil];
}

- (void) appendData:(NSMutableData*) data byName:(NSString*) name value:(NSString*) value
{
    [data appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
	[data appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",name, value] dataUsingEncoding:NSUTF8StringEncoding]];
    
}

- (void) appendData:(NSMutableData*) data byName:(NSString*) name fileName:(NSString*) fName fileData:(NSData*) fileData
{
    [data appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [data appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n" , name, fName] dataUsingEncoding:NSUTF8StringEncoding]];
	[data appendData:[@"Content-Type: application/octet-stream\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
	[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
	[data appendData:fileData];

}

- (void) postData:(NSData*)data
{
	if(canceled)
		return;
        
    //Test 002 begin
    NSURL *httpsURL = [NSURL URLWithString:[[HttpServerURL GetInstance] uploadServerURL]];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:httpsURL];
//    [request setURL:httpsURL];    
    //超时时间
//    request.timeOutSeconds = 30;
    
    [request setRequestMethod:@"POST"];
    
    //定义异步方法    
    [request addPostValue:businessType forKey:@"BUSINESS_TYPE"];
    [request addPostValue:businessID forKey:@"BUSINESS_ID"];
    [request addPostValue:memberID forKey:@"MEMBER_ID"];
    [request addPostValue:fileType forKey:@"FILE_TYPE"];
    [request addPostValue:fileName forKey:@"FILE_NAME"];
//    [request addPostValue:fileID forKey:@"FILE_ID"];
    NSLog(@"postBody(BUSINESS_ID=%@;BUSINESS_TYPE=%@;MEMBER_ID=%@;FILE_TYPE=%@;FILE_NAME=%@",businessID,businessType,memberID,fileType,fileName);
    [request addData:data withFileName:@"myphoto.jpg" andContentType:@"image/jpeg" forKey:@"file"];
    
    [request buildRequestHeaders];
    
    //开始执行
    [request setValidatesSecureCertificate:NO];
    request.shouldAttemptPersistentConnection   = NO;
//    [request setDelegate:self];
    [request setShowAccurateProgress:YES];
//    [request startAsynchronous];
    [request startSynchronous];
    
//    NSData *response=[request responseData];
//    NSString *tmpData=[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//    NSLog(@"tmpData=%@",tmpData);
//    [tmpData release];
    NSLog(@"responseString = %@", request.responseString);

    NSError* error = [request error];
    if (!error) 
    {        
        XmlParser *xmlParser = [[XmlParser alloc] init];
        NSData *data = [request responseData];
        NSString *tmpData=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"responseData = %@", tmpData);
        [tmpData release];
        [xmlParser XmlToArray:data];
        
//        NSMutableArray *tmpArray=[[NSMutableArray alloc] initWithArray:[xmlParser GetReturnArray]];
        NSMutableArray *tmpArray=[xmlParser GetReturnArray];
        
        if ([tmpArray count] > 0){
            NSLog(@"response count:%d",[[tmpArray objectAtIndex:0] count]);
        
            [[InfoType share] SetTranValueDict:[tmpArray objectAtIndex:0]];
        }else{
            [[InfoType share] SetTranValueDict:nil];
        }
        
//        [tmpArray release];
//        [xmlParser release];
    
    } 
    else
    {
        NSLog(@"Failed to save to data store: %@", [error localizedDescription]);
    }
    //Test 002 end

}

- (void) postData:(NSData*)data contentType:(NSString*)mediaContentType
{
	self.contentType = mediaContentType;
	[self postData:data];
}


- (void)postJPEGData:(NSData*)imageJPEGData delegate:(id <FileUploaderDelegate>)dlgt userData:(id)data
{
	self.delegate = dlgt;
	self.userData = data;
	
	if(!imageJPEGData)
	{
		[delegate uploadedImage:nil sender:self];
		return;
	}
		

	[self postData:imageJPEGData contentType:JPEG_CONTENT_TYPE];
}

- (void)postMP4Data:(NSData*)movieData delegate:(id <FileUploaderDelegate>)dlgt userData:(id)data
{
	self.delegate = dlgt;
	self.userData = data;
	
	if(!movieData)
	{
		[delegate uploadedImage:nil sender:self];
		return;
	}
		

	[self postData:movieData contentType:MP4_CONTENT_TYPE];
}

- (void)convertImageThreadAndStartUpload:(UIImage*)image
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	NSData* imData = UIImageJPEGRepresentation(image, 1.0f);
	self.contentType = JPEG_CONTENT_TYPE;
	[self performSelectorOnMainThread:@selector(postData:) withObject:imData waitUntilDone:NO];

	[pool release];
}

- (void)postImage:(UIImage*)image delegate:(id <FileUploaderDelegate>)dlgt userData:(id)data
{
	delegate = [dlgt retain];
	self.userData = data;

	UIImage* modifiedImage = nil;

	[NSThread detachNewThreadSelector:@selector(convertImageThreadAndStartUpload:) toTarget:self withObject:modifiedImage ? modifiedImage : image];
}


#pragma mark -  
#pragma mark ASI HTTP Request Methods  
-(void) requestFinished:(ASIHTTPRequest *)request1{
	if ([result length]==0) {
		return ;
	}
    //	progressLabel.text=[NSString stringWithFormat:@"100％"];
    NSString *str=[request1 responseString];
    NSLog(@"=========%@",str);
}

-(void) requestFailed:(ASIHTTPRequest *)request1{
	NSString *error=[[request1 error] description];
	NSLog(@"requestFailed=%@",error);
}

-(void) request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data{
	[result appendData:data];
	
	NSLog(@"didReceiveData");
}

-(void) request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders{
	if (result==nil) {
		result=[[NSMutableData data] retain];
	}
	[result setLength:0];
    NSLog(@"didReceiveResponseHeaders==%@",[responseHeaders allKeys]);
	
}


#pragma mark NSURLConnection delegate methods


- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [result setLength:0];
}


- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [result appendData:data];
}


- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//	[ decreaseNetworkActivityIndicator];

	[delegate uploadedImage:nil sender:self];
    [self release];
}


- (NSCachedURLResponse *) connection:(NSURLConnection *)connection 
                   willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
     return cachedResponse;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if (qName) 
        elementName = qName;

    if ([elementName isEqualToString:@"mediaurl"])
		self.contentXMLProperty = [NSMutableString string];
	else
		self.contentXMLProperty = nil;
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{     
    if (qName)
        elementName = qName;
    
    if ([elementName isEqualToString:@"mediaurl"])
	{
        self.anewURL1 = [self.contentXMLProperty stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
		[parser abortParsing];
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (self.contentXMLProperty)
		[self.contentXMLProperty appendString:string];
}


- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
//	[ decreaseNetworkActivityIndicator];

	NSXMLParser *parser = [[NSXMLParser alloc] initWithData:result];
	[parser setDelegate:self];
	[parser setShouldProcessNamespaces:NO];
	[parser setShouldReportNamespacePrefixes:NO];
	[parser setShouldResolveExternalEntities:NO];
	
	[parser parse];
	[parser release];

	[result setLength:0];
	
	[delegate uploadedImage:@"scuess" sender:self];
	[self release];
}

- (void)cancel
{
	canceled = YES;
//	if(connection)
//	{
//		[connection cancel];
////		[ decreaseNetworkActivityIndicator];
//		[self release];
//	}
	[delegate uploadedImage:nil sender:self];
}

- (BOOL)canceled
{
	return canceled;
}


@end
